﻿using System.Collections.Generic;
using System.Web.Mvc;

namespace RefLib.MVC.JsonModels
{
    public sealed class ValidationJsonModel
    {
        public static ValidationJsonModel FromModelStateDictionary(ModelStateDictionary msd)
        {
            var model = new ValidationJsonModel();
            model.isValid = msd.IsValid;

            if (! model.isValid)
            {
                foreach (string key in msd.Keys)
                {
                    ModelState modelState = msd[key];
                    if (modelState.Errors != null && modelState.Errors.Count > 0)
                    {
                        Error error = new Error() { errorMessage = "", fieldName = key };
                        foreach (ModelError me in modelState.Errors)
                        {
                            error.errorMessage += " " + me.ErrorMessage;
                        }
                        model.errors.Add(error);
                    }
                }
            }

            return model;
        }

        public class Error
        {
            public string errorMessage { get; set; }
            public string fieldName { get; set; }
        }

        public List<Error> errors = new List<Error>();
        public bool isValid { get; set; }

        private ValidationJsonModel() { }
    }
}
